package cn.lzh.controller;

import cn.lzh.entity.Hot;
import cn.lzh.entity.Largefile;
import cn.lzh.service.HotService;
import cn.lzh.service.LargefileService;
import cn.lzh.tool.RespJson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


@CrossOrigin//允许跨域
@RestController
@RequestMapping("/api/adm/hot")
public class HotController {
    @Autowired
    HotService hotService;
    @Autowired
    LargefileService largefileService;

    //查询全部
    @RequestMapping("/findAll")
    public Map <String,Object> findAll(){
       List<Hot> list =  hotService.findAll();
      return RespJson.pack(200,"查询成功",list);
    }


    //添加
    @RequestMapping("/addHot")
    public Map<String,Object>addHot(Hot hot, @RequestParam("pic")
            MultipartFile file)throws Exception{
        Largefile largefile = new Largefile();
        if(file!=null&&file.getSize()>0){
            largefile.setFilename(file.getOriginalFilename());  //添加filename 名字
            String uuid=UUID.randomUUID().toString();  //uuid 获取唯一的标识符
            largefile.setId(uuid);
            byte[] buf = file.getBytes();   //  得到长度
            largefile.setContent(buf);    //添加文件
        }
        if(largefile.getId()!=null){
            hot.setPicture(largefile.getId());  //Picture是largefile id的值
            largefileService.addLargefile(largefile);

        }
        hotService.addHot(hot);
        return RespJson.pack(200, "添加成功",hot);
    }


      //删除
    @RequestMapping("/delete/{id}")
public Map<String,Object> delete(@PathVariable  Integer id){
         Hot hot = hotService.finsByid(id);

         largefileService.delete(hot.getPicture());
    int i = hotService.delete(id);
    System.out.println(i);
    return RespJson.pack(200,"删除成功",null);
}
}
